25. Exercise: Foreground vs. Background

L1 A25 Handling Messages In Foreground Vs Background

Exercise

You want to make sure the user sees a notification popping up as a reminder so let’s implement some code to trigger a notification.

  1. To do that, open the onMessageReceived() function in MyFirebaseMessagingService again. Right after the code you recently added to check the data message, you will add code which sends a notification using the notifications framework.
// MyFirebaseMessagingService.kt

        // TODO: Step 3.6 check messages for notification and call sendNotification
        // Check if message contains a notification payload.
        remoteMessage?.notification?.let {
            Log.d(TAG, "Message Notification Body: ${it.body}")
            sendNotification(it.body!!)
        }
  1. Check notification property and the remoteObject is not nulland call the sendNotification function. sendNotification functions gets an instance of NotificationManager and calls the sendNotification extension function you previously wrote.



  2. If you run the app again and send a notification by using Notifications composer, you should see a notification regardless of if the app is in foreground or background.